<template>
  <div
    class="result-item"
    :class="{ 'selected': isSelected }"
    @click="$emit('toggleSelection', result)"
  >
    <div class="result-checkbox">
      <el-checkbox
        :model-value="isSelected"
        @change="$emit('toggleSelection', result)"
        @click.stop
      />
    </div>

    <div class="result-content" @click="$emit('fileSelect', result)">
      <div class="result-header">
        <div class="file-info">
          <el-icon class="file-icon">
            <Document />
          </el-icon>
          <span class="file-name" v-html="highlightText(result.fileName, query)"></span>
          <el-tag size="small" type="info">{{ getFileExtension(result.fileName) }}</el-tag>
        </div>
        
        <div class="result-meta">
          <span class="version-id">{{ result.versionId }}</span>
          <span class="timestamp">{{ formatTimestamp(result.timestamp) }}</span>
          <span class="match-score">匹配度: {{ Math.round(result.matchScore * 100) }}%</span>
        </div>
      </div>

      <div class="file-path">
        <el-icon><Folder /></el-icon>
        <span v-html="highlightText(result.originalPath, query)"></span>
      </div>

      <!-- 内容搜索结果的匹配片段 -->
      <div v-if="isContentResult(result)" class="content-matches">
        <div
          v-for="(match, matchIndex) in result.matches.slice(0, 3)"
          :key="matchIndex"
          class="content-match"
        >
          <div class="match-line-number">第 {{ match.lineNumber }} 行:</div>
          <div class="match-content">
            <span v-html="highlightMatch(match.lineContent, match.matchStart, match.matchEnd)"></span>
          </div>
          
          <!-- 上下文 -->
          <div v-if="match.context.length > 0" class="match-context">
            <div
              v-for="(contextLine, contextIndex) in match.context"
              :key="contextIndex"
              class="context-line"
            >
              {{ contextLine }}
            </div>
          </div>
        </div>
        
        <div v-if="result.matches.length > 3" class="more-matches">
          还有 {{ result.matches.length - 3 }} 个匹配项...
        </div>
      </div>
    </div>

    <div class="result-actions">
      <el-button-group size="small">
        <el-button @click.stop="$emit('fileSelect', result)">
          <el-icon><View /></el-icon>
          查看
        </el-button>
        <el-button @click.stop="$emit('recoverFile', result)">
          <el-icon><Download /></el-icon>
          恢复
        </el-button>
      </el-button-group>
    </div>
  </div>
</template>

<script setup lang="ts">
import { Document, Folder, View, Download } from '@element-plus/icons-vue'
import type { SearchResult, ContentSearchResult } from '../types/basic'

interface Props {
  result: SearchResult | ContentSearchResult
  query: string
  isSelected: boolean
}

interface Emits {
  (e: 'toggleSelection', result: SearchResult | ContentSearchResult): void
  (e: 'fileSelect', result: SearchResult | ContentSearchResult): void
  (e: 'recoverFile', result: SearchResult | ContentSearchResult): void
}

defineProps<Props>()
defineEmits<Emits>()

// 判断是否为内容搜索结果
function isContentResult(result: SearchResult | ContentSearchResult): result is ContentSearchResult {
  return 'matches' in result
}

// 高亮显示搜索关键词
function highlightText(text: string, query: string): string {
  if (!query || !text) return text
  
  const regex = new RegExp(`(${escapeRegExp(query)})`, 'gi')
  return text.replace(regex, '<mark class="search-highlight">$1</mark>')
}

// 高亮显示匹配内容
function highlightMatch(content: string, start: number, end: number): string {
  if (!content) return ''
  
  const before = content.substring(0, start)
  const match = content.substring(start, end)
  const after = content.substring(end)
  
  return `${before}<mark class="content-highlight">${match}</mark>${after}`
}

// 转义正则表达式特殊字符
function escapeRegExp(string: string): string {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}

// 获取文件扩展名
function getFileExtension(fileName: string): string {
  const ext = fileName.split('.').pop()
  return ext ? ext.toUpperCase() : 'FILE'
}

// 格式化时间戳
function formatTimestamp(timestamp: number): string {
  return new Date(timestamp).toLocaleString('zh-CN')
}
</script>

<style scoped>
.result-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  margin-bottom: 12px;
  border: 1px solid var(--el-border-color-light);
  border-radius: 8px;
  background-color: var(--el-bg-color);
  transition: all 0.2s;
  cursor: pointer;
}

.result-item:hover {
  border-color: var(--el-color-primary-light-7);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.result-item.selected {
  border-color: var(--el-color-primary);
  background-color: var(--el-color-primary-light-9);
}

.result-checkbox {
  flex-shrink: 0;
  margin-top: 2px;
}

.result-content {
  flex: 1;
  min-width: 0;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  min-width: 0;
}

.file-icon {
  color: var(--el-color-primary);
  flex-shrink: 0;
}

.file-name {
  font-weight: 600;
  color: var(--el-text-color-primary);
  word-break: break-all;
}

.result-meta {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 12px;
  color: var(--el-text-color-regular);
  flex-shrink: 0;
}

.version-id {
  font-family: monospace;
  background-color: var(--el-color-info-light-8);
  padding: 2px 6px;
  border-radius: 4px;
}

.match-score {
  color: var(--el-color-success);
  font-weight: 600;
}

.file-path {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  color: var(--el-text-color-regular);
  margin-bottom: 8px;
}

.content-matches {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid var(--el-border-color-lighter);
}

.content-match {
  margin-bottom: 12px;
  padding: 8px;
  background-color: var(--el-color-info-light-9);
  border-radius: 6px;
}

.content-match:last-child {
  margin-bottom: 0;
}

.match-line-number {
  font-size: 12px;
  color: var(--el-color-primary);
  font-weight: 600;
  margin-bottom: 4px;
}

.match-content {
  font-family: monospace;
  font-size: 13px;
  line-height: 1.4;
  margin-bottom: 6px;
}

.match-context {
  margin-top: 6px;
}

.context-line {
  font-family: monospace;
  font-size: 12px;
  color: var(--el-text-color-secondary);
  line-height: 1.3;
  padding-left: 16px;
  border-left: 2px solid var(--el-border-color-lighter);
}

.more-matches {
  font-size: 12px;
  color: var(--el-text-color-secondary);
  font-style: italic;
  text-align: center;
  margin-top: 8px;
}

.result-actions {
  flex-shrink: 0;
}

/* 高亮样式 */
:deep(.search-highlight) {
  background-color: var(--el-color-warning-light-8);
  color: var(--el-color-warning-dark-2);
  padding: 1px 2px;
  border-radius: 2px;
  font-weight: 600;
}

:deep(.content-highlight) {
  background-color: var(--el-color-primary-light-8);
  color: var(--el-color-primary-dark-2);
  padding: 1px 2px;
  border-radius: 2px;
  font-weight: 600;
}
</style>